package com.example.util;

import java.util.logging.*;

/**
 * @Classname LogUtils
 * @Description TODO
 * @Date 2023/4/26 16:00
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class LogUtils {

    private static Logger SYSTEM_LOGGER ;

    public static void info(String msg){
        Logger logger=getLogger();
        logger.info(msg);
    }

    public static void severe(String msg){
        Logger logger=getLogger();
        logger.severe(msg);
    }

    public static void warning(String msg){
        Logger logger=getLogger();
        logger.warning(msg);
    }

    private static Logger getLogger(){
        if(SYSTEM_LOGGER==null){
            ConsoleHandler consoleHandler = new ConsoleHandler();
            // 创建自定义格式化程序
            ColoredFormatter formatter = new ColoredFormatter();
            consoleHandler.setFormatter(formatter);
            SYSTEM_LOGGER = Logger.getLogger(LogUtils.class.getName());
            SYSTEM_LOGGER.addHandler(consoleHandler);
            SYSTEM_LOGGER.setLevel(Level.ALL);
        }
        return SYSTEM_LOGGER;
    }

    static class ColoredFormatter extends Formatter {
        private static final String RESET_COLOR = "\u001B[0m";
        private static final String WHITE_COLOR = "\u001B[1m";  //白色
        private static final String SEVERE_COLOR = "\u001B[35m";  // 紫色
        private static final String WARNING_COLOR = "\u001B[33m"; // 黄色
        private static final String COLOR_INFO = "\u001B[34m"; // 蓝色
        private static final String COLOR_CYAN = "\u001B[36m"; // 青色

        @Override
        public String format(LogRecord record) {
            StringBuilder sb = new StringBuilder();
            String levelName = record.getLevel().getName();
            if (levelName.equals("SEVERE")) {
                sb.append(SEVERE_COLOR);
            } else if (levelName.equals("WARNING")) {
                sb.append(WARNING_COLOR);
            }else if(levelName.equals("INFO")) {
                sb.append(COLOR_CYAN);
            }else {
                sb.append(WHITE_COLOR);
            }
            sb.append(levelName);
            sb.append(": ");
            sb.append(formatMessage(record));
            sb.append("\n");
            return sb.toString();
        }
    }
}
